// 客户管理功能实现

DOM.on(window, 'load', () => {
  let currentPage = 1;
  const pageSize = 10;
  
  // 渲染客户表格
  function renderCustomers() {
    const customersTable = DOM.$('#customers-table tbody');
    customersTable.innerHTML = '';
    
    const customers = dataManager.data.customers;
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedCustomers = customers.slice(startIndex, endIndex);
    const totalPages = Math.ceil(customers.length / pageSize);
    
    if (paginatedCustomers.length === 0) {
      const emptyRow = DOM.create('tr');
      emptyRow.innerHTML = `
        <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
          暂无客户数据
        </td>
      `;
      customersTable.appendChild(emptyRow);
      return;
    }
    
    paginatedCustomers.forEach(customer => {
      const row = DOM.create('tr');
      
      // 格式化注册日期
      const registerDate = new Date(customer.registerDate).toLocaleDateString('zh-CN');
      
      row.innerHTML = `
        <td>${customer.id}</td>
        <td>${customer.name}</td>
        <td>${customer.email}</td>
        <td>${customer.phone}</td>
        <td>${registerDate}</td>
        <td>${customer.orderCount}</td>
        <td>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-customer-id="${customer.id}" data-action="view">
            查看
          </button>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px;" data-customer-id="${customer.id}" data-action="orders">
            订单
          </button>
        </td>
      `;
      
      customersTable.appendChild(row);
    });
    
    // 绑定操作按钮事件
    bindCustomerActions();
    
    // 渲染分页
    renderPagination(totalPages, currentPage);
  }
  
  // 绑定客户操作按钮事件
  function bindCustomerActions() {
    DOM.$$('#customers-table [data-action]').forEach(btn => {
      DOM.on(btn, 'click', () => {
        const customerId = btn.getAttribute('data-customer-id');
        const action = btn.getAttribute('data-action');
        
        switch (action) {
          case 'view':
            viewCustomerDetail(customerId);
            break;
          case 'orders':
            viewCustomerOrders(customerId);
            break;
        }
      });
    });
  }
  
  // 查看客户详情
  function viewCustomerDetail(customerId) {
    const customer = dataManager.data.customers.find(c => c.id === customerId);
    if (customer) {
      let details = `客户详情\n\n`;
      details += `客户ID: ${customer.id}\n`;
      details += `姓名: ${customer.name}\n`;
      details += `邮箱: ${customer.email}\n`;
      details += `电话: ${customer.phone}\n`;
      details += `注册日期: ${new Date(customer.registerDate).toLocaleDateString('zh-CN')}\n`;
      details += `订单数量: ${customer.orderCount}\n`;
      details += `消费总额: ¥${customer.totalSpent.toFixed(2)}\n`;
      
      // 计算平均订单金额
      const avgOrderAmount = customer.orderCount > 0 ? 
        (customer.totalSpent / customer.orderCount).toFixed(2) : '0.00';
      details += `平均订单金额: ¥${avgOrderAmount}\n`;
      
      alert(details);
    }
  }
  
  // 查看客户订单
  function viewCustomerOrders(customerId) {
    const customer = dataManager.data.customers.find(c => c.id === customerId);
    const orders = dataManager.data.orders.filter(o => o.customer.id === customerId);
    
    if (customer && orders.length > 0) {
      let details = `${customer.name} 的订单记录\n\n`;
      
      orders.forEach((order, index) => {
        details += `${index + 1}. 订单号: ${order.id}\n`;
        details += `   金额: ¥${order.totalAmount.toFixed(2)}\n`;
        details += `   状态: ${orderStatusMachine.getStateLabel(order.status)}\n`;
        details += `   日期: ${new Date(order.createdAt).toLocaleDateString('zh-CN')}\n\n`;
      });
      
      alert(details);
    } else if (customer) {
      alert(`${customer.name} 暂无订单记录`);
    }
  }
  
  // 渲染分页控件
  function renderPagination(totalPages, current) {
    // 移除旧的分页控件
    const oldPagination = DOM.$('#customers-table + .pagination');
    if (oldPagination) {
      oldPagination.remove();
    }
    
    // 创建新的分页控件
    const tableContainer = DOM.$('#customers-table').parentElement;
    const pagination = DOM.create('div', 'pagination');
    
    // 上一页
    const prevBtn = DOM.create('button');
    prevBtn.innerHTML = '‹';
    prevBtn.disabled = current === 1;
    DOM.on(prevBtn, 'click', () => {
      if (current > 1) {
        currentPage--;
        renderCustomers();
      }
    });
    pagination.appendChild(prevBtn);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
      const pageBtn = DOM.create('button');
      pageBtn.textContent = i;
      if (i === current) {
        pageBtn.classList.add('active');
      }
      DOM.on(pageBtn, 'click', () => {
        currentPage = i;
        renderCustomers();
      });
      pagination.appendChild(pageBtn);
    }
    
    // 下一页
    const nextBtn = DOM.create('button');
    nextBtn.innerHTML = '›';
    nextBtn.disabled = current === totalPages;
    DOM.on(nextBtn, 'click', () => {
      if (current < totalPages) {
        currentPage++;
        renderCustomers();
      }
    });
    pagination.appendChild(nextBtn);
    
    tableContainer.appendChild(pagination);
  }
  
  // 导出客户数据
  function exportCustomers() {
    const customers = dataManager.data.customers.map(customer => ({
      id: customer.id,
      name: customer.name,
      email: customer.email,
      phone: customer.phone,
      registerDate: customer.registerDate,
      orderCount: customer.orderCount,
      totalSpent: customer.totalSpent
    }));
    
    dataManager.exportToCSV(customers, `客户数据_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.csv`);
  }
  
  // 初始化客户管理页面
  function initCustomers() {
    // 绑定导出客户按钮事件
    const exportBtn = DOM.$('#customers-view .btn-secondary');
    if (exportBtn) {
      DOM.on(exportBtn, 'click', exportCustomers);
    }
    
    // 监听视图切换事件
    DOM.on(document, 'viewChanged', (e) => {
      if (e.detail.viewId === 'customers') {
        currentPage = 1;
        renderCustomers();
      }
    });
  }
  
  // 初始化
  initCustomers();
});